package LearnDataStructure.a_线性结构.例题;

/**
 * @version: 1.0
 * @Author: wuqiu
 * @date: 2023-07-03 13:30
 * @description: LeetcodeLearnAlgorithm -> LearnDataStructure.a_线性结构.例题
 */
public class b_倒数第k个节点by单向链表and快行指针 {
    public static void main(String[] args) {
        b_倒数第k个节点by单向链表and快行指针 test = new b_倒数第k个节点by单向链表and快行指针();
        int[] arr = new int[]{9, 8, 7, 6, 6, 4, 2, 11, 11, 3, 4};
        test.useFindEndK(arr,3);
    }

    /**
     * 链表不能为空，K不能不满足题意
     * 意外的数据处理我没做，懒得做了
     * @param arr
     * @param k
     */
    public void useFindEndK(int[] arr, int k) {
        if (k > arr.length || k <= 0 ||arr.length == 0) {
            return;
        }
        CaseNode head = new CaseNode(arr[0]);
        CaseNode p = head;
        for (int i = 1; i < arr.length; i++) {
            p.next = new CaseNode(arr[i]);
            p = p.next;
        }
        CaseNode endK = findEndK(head, k);
        System.out.println(endK.data);
    }

    public CaseNode findEndK(CaseNode head, int k) {
        CaseNode p = head;
        CaseNode fast = head;
        for (int i = 0; i < k; i++) {
            if (fast == null) {//防止因k过大，而出错
                return null;
            }
            fast = fast.next;
        }
        while (fast != null) {
            p = p.next;
            fast = fast.next;
        }
        return p;
    }
}
